package com.jiutong.meipenggang.ui.activitys;


import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.jiutong.meipenggang.R;
import com.jiutong.meipenggang.base.AppManager;
import com.jiutong.meipenggang.base.BaseActivity;
import com.jiutong.meipenggang.common.Constants;
import com.jiutong.meipenggang.entity.BaseBean;
import com.jiutong.meipenggang.entity.GestureLoginBean;
import com.jiutong.meipenggang.http.model.interfaces.GestureBiz;
import com.jiutong.meipenggang.http.present.GesturePresent;
import com.jiutong.meipenggang.utils.EncryptUtil;
import com.jiutong.meipenggang.utils.NumUilt;
import com.jiutong.meipenggang.utils.SpConfig;
import com.jiutong.meipenggang.views.GlideCircleTransform;
import com.jiutong.meipenggang.views.RoundImageView;
import com.jiutong.meipenggang.views.gesturelock.widget.GestureContentView;
import com.jiutong.meipenggang.views.gesturelock.widget.GestureDrawline;
import com.orhanobut.logger.Logger;

public class GestureVerifyActivity extends BaseActivity implements View.OnClickListener, GestureBiz {
    /**
     * 手机号码
     */
    public static final String PARAM_PHONE_NUMBER = "PARAM_PHONE_NUMBER";
    /**
     * 意图
     */
    public static final String PARAM_INTENT_CODE = "PARAM_INTENT_CODE";
    private RelativeLayout mTopLayout;
    private TextView mTextTitle;
    private TextView mTextCancel;
    private RoundImageView mImgUserLogo;
    private TextView mTextPhoneNumber;
    private TextView mTextTip;
    private FrameLayout mGestureContainer;
    private GestureContentView mGestureContentView;
    private TextView mTextForget;
    private RelativeLayout rl_back;
    //    private TextView mTextOther;
    private String mParamPhoneNumber;
    private long mExitTime = 0;
    private int mParamIntentCode;
    private SharedPreferences mSharedPreferences;
    private int count = 4;
    private String phone;
    private String imgpath = "";
    private boolean change_shoushi = false;
    private String inputCode;

    private GesturePresent gesturePresent;


    @Override
    public int getLayoutResouceId() {
        return R.layout.activity_gesture_verify;
    }


    @Override
    protected void onResume() {
        super.onResume();
        gesturePresent = new GesturePresent(this, this);
        change_shoushi = SpConfig.getInstance().getBool(Constants.CHANGE_SHOUSHI);
        ObtainExtraData();

        setUpViews();

        setUpListeners();
    }

    private void ObtainExtraData() {
        mParamPhoneNumber = getIntent().getStringExtra(PARAM_PHONE_NUMBER);
        mParamIntentCode = getIntent().getIntExtra(PARAM_INTENT_CODE, 0);
        mSharedPreferences = this.getSharedPreferences("secret_protect", Context.MODE_PRIVATE);
    }

    private void setUpViews() {
        mTopLayout = (RelativeLayout) findViewById(R.id.top_layout);
        mTextTitle = (TextView) findViewById(R.id.text_title);
        mTextCancel = (TextView) findViewById(R.id.text_cancel);
        mImgUserLogo = (RoundImageView) findViewById(R.id.user_logo);
        imgpath = SpConfig.getInstance().getString(Constants.IMAGE_PATH);
        if (!TextUtils.isEmpty(imgpath)) {
            Glide.with(this).load(imgpath).transform(new CenterCrop(this), new GlideCircleTransform(this))
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .crossFade().into(mImgUserLogo);
        } else {
            mImgUserLogo.setImageResource(R.mipmap.icon_personal);
        }
        mTextPhoneNumber = (TextView) findViewById(R.id.text_phone_number);
        mTextTip = (TextView) findViewById(R.id.text_tip);
        mGestureContainer = (FrameLayout) findViewById(R.id.gesture_container);
        mTextForget = (TextView) findViewById(R.id.text_forget_gesture);
        mTextForget.setTextColor(getResources().getColor(R.color.gesture_color));
        rl_back = (RelativeLayout) findViewById(R.id.rl_gestureVerify_back);
        if (!SpConfig.getInstance().getBool(Constants.CHANGE_SHOUSHI)) {
            mTextForget.setVisibility(View.VISIBLE);
        } else {
            mTextForget.setVisibility(View.GONE);
        }
        rl_back.setVisibility(View.VISIBLE);
//        mTextOther = (TextView) findViewById(R.id.text_other_account);
        phone = SpConfig.getInstance().getString(Constants.USERNAME_STRING);
        if (!TextUtils.isEmpty(phone)) {
            mTextPhoneNumber.setText(NumUilt.phoneFormat(phone));
        }

        inputCode = SpConfig.getInstance().getString(Constants.SHOU_SHI);
        if (TextUtils.isEmpty(inputCode))
            return;

        // 初始化一个显示各个点的viewGroup
        mGestureContentView = new GestureContentView(this, true, inputCode,
                new GestureDrawline.GestureCallBack() {

                    @Override
                    public void onGestureCodeInput(String inputCode) {

                    }

                    @Override
                    public void checkedSuccess() {

                        mGestureContentView.clearDrawlineState(0L);
                        if (change_shoushi) {
                            toastShortShow("验证成功");
                            openActivity(GestureEditActivity.class);
                            Logger.d("shoushi",SpConfig.getInstance().getString(Constants.SHOU_SHI));
                            finish();
                        } else {
                            //手势密码登录成功
                            gesturePresent.gestureLogin();
                        }

                    }

                    @Override
                    public void checkedFail() {
                        if (count == 0) {
                            openActivity(LoginedActivity.class);
                            SpConfig.getInstance().edit().putString(Constants.SHOU_SHI, "").commit();
                            finish();
                            return;
                        }
                        mGestureContentView.clearDrawlineState(1300L);
                        mTextTip.setVisibility(View.VISIBLE);
                        mTextTip.setText("密码错误，你还可以输入" + count + "次");
                        count--;
                        // 左右移动动画
                        Animation shakeAnimation = AnimationUtils.loadAnimation(GestureVerifyActivity.this, R.anim.shake);
                        mTextTip.startAnimation(shakeAnimation);

                    }
                });

        // 设置手势解锁显示到哪个布局里面
        mGestureContentView.setParentView(mGestureContainer);
    }

    private void setUpListeners() {
        mTextCancel.setOnClickListener(this);
        mTextForget.setOnClickListener(this);
//        mTextOther.setOnClickListener(this);
        rl_back.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.text_cancel:
                finish();
                break;
            case R.id.text_forget_gesture:
                Bundle bundle = new Bundle();
                bundle.putBoolean("forget", true);
                openActivity(LoginedActivity.class, bundle);
                finish();
                break;
            case R.id.rl_gestureVerify_back:
                if (!SpConfig.getInstance().getBool(Constants.CHANGE_SHOUSHI)) {
                    SpConfig.getInstance().edit().putBoolean(Constants.IS_LOGIN, false).commit();
//                    openActivity(MainActivity.class);
                }
                finish();
                break;
            default:
                break;
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!change_shoushi) {
                SpConfig.getInstance().edit().putBoolean(Constants.IS_LOGIN, false).commit();
//                openActivity(MainActivity.class);
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public String gesturePassword() {
        return inputCode;
    }

    @Override
    public String gestureCipher() {
        return SpConfig.getInstance().getString(Constants.GESTURE_CIPHER);
    }

    @Override
    public void onSuccess(Object object) {
        GestureLoginBean gestureLoginBean = (GestureLoginBean) object;
        if (gestureLoginBean.getError() == -1) {
            toastShortShow(gestureLoginBean.getMsg());
            SpConfig.getInstance().edit().putBoolean(Constants.IS_LOGIN, true).commit();
            SpConfig.getInstance().edit().putBoolean(Constants.BIND_CARD_FLAG, gestureLoginBean.isBindCardFlag()).commit();
            SpConfig.getInstance().edit().putString(Constants.ID, gestureLoginBean.getId()).commit();
            SpConfig.getInstance().edit().putInt(Constants.USER_ID, gestureLoginBean.getUserId()).commit();
            SpConfig.getInstance().edit().putString(Constants.TOKEN, gestureLoginBean.getToken()).commit();
            SpConfig.getInstance().edit().putBoolean(Constants.TOKEN_FAIL,false).commit();
            finish();
        } else {
            toastShortShow(gestureLoginBean.getMsg());
        }
    }

    @Override
    public void onError(Throwable e) {

    }

    @Override
    public int getOpt() {
        return 0;
    }
}
